DAY21:Highest Scoring Word


Posted by birdbirdmurmur on 2023-08-03

題目連結

Highest Scoring Word

解法

Javascript

function high(x){
  function calculateScore (word){
    const alphabet = "abcdefghijklmnopqrstuvwxyz"
    return word.split('').reduce( (score, letter) => score + alphabet.indexOf(letter) + 1 , 0)
  }

  const words = x.split(' ')
  let highestWord = ''
  let highestScore = 0

  words.forEach( (word) => {
    const score = calculateScore(word)
    if (score > highestScore || (score === highestScore && word < highestWord.length)){
        highestScore = score
        highestWord = word
        }
  })
    return highestWord
}

心得

先把x用split(' ')做拆解
預設兩個值:最高分數最高分單字
將拆解後的words進迴圈比大小
同時建立一個轉換分數的function
如果轉換後的分數大於highestScorehighestWord就替換掉
同分就比單字的長度
最後回傳(每次都忘記回傳 不然就是設立在迴圈裡頭)


#javascript #Codewars







Related Posts

1. 開始java 17前,我們先快速了解一下spring boot

1. 開始java 17前,我們先快速了解一下spring boot

How to build CICD with Jenkins as code based on container

How to build CICD with Jenkins as code based on container

大公司 vs 小公司

大公司 vs 小公司


Comments